package com.naver.analysis;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import joptsimple.OptionParser;
import joptsimple.OptionSet;

public class FromWebLogToTPS {
	public static void main(String[] args) throws IOException {
		OptionParser parser = new OptionParser();
		parser.accepts("F").withRequiredArg().ofType(File.class).describedAs("log file's full path");
		parser.accepts("T").withRequiredArg().ofType(String.class).describedAs("ex. 2012:17:00");
		parser.accepts("P").withRequiredArg().ofType(String.class).describedAs("text");
		parser.accepts("S").withRequiredArg().ofType(Integer.class).describedAs("server count");
		OptionSet options = parser.parse(args);

		if (!(options.has("P") && options.nonOptionArguments().isEmpty())) {
			parser.printHelpOn(System.out);
			System.exit(1);
		}
		FromWebLogToTPS main = new FromWebLogToTPS();
		main.execute((File)options.valueOf("F"), (String)options.valueOf("T"), (String)options.valueOf("P"), (Integer)options.valueOf("S"));
	}

	private void execute(File logFile, String time, String text, int serverCount) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(logFile));
		String line = null;
		Map<Integer, Integer> eachCount = new TreeMap<Integer, Integer>();

		while (null != (line = reader.readLine())) {
			String ft = line.substring(line.indexOf("2012:"), line.indexOf(" +0900"));
			String fm = ft.substring(0, 10);

			if (fm.equals(time)) {
				for (int s = 0; s < 60; s++) {
					if (String.format("%s:%02d", time, s).equals(ft)) {
						if (line.contains(text)) {
							if (eachCount.containsKey(s)) {
								int currVal = eachCount.get(s);
								eachCount.put(s, ++currVal);
							} else {
								eachCount.put(s, 1);
							}
						}
					}
				}
			}
		}

		Iterator<Integer> iterator = eachCount.keySet().iterator();

		int total = 0;
		int minVal = Integer.MAX_VALUE;
		int maxVal = Integer.MIN_VALUE;
		while (iterator.hasNext()) {
			int key = iterator.next();
			int value = eachCount.get(key);

			if (value < minVal) {
				minVal = value;
			}

			if (value > maxVal) {
				maxVal = value;
			}
			total += value;
			System.out.println(String.format("[%d]-%d", key, value));
		}
		System.out.println(String.format("each AVG : %d, MIN : %d, MAX : %d", total / 60, minVal, maxVal));
		System.out.println(String.format("all AVG : %d, MIN : %d, MAX : %d", (total / 60) * serverCount, minVal * serverCount, maxVal * serverCount));
		System.out.println(String.format("max : %d(%d)", maxVal * 2, maxVal * serverCount * 2));
	}
}
